package com.teach.api;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teach.Const;
import com.teach.R;
import com.teach.dto.LoginUser;
import com.teach.dto.UserRegDTO;
import com.teach.dto.UserSearch;
import com.teach.entity.User;
import com.teach.service.UserService;
import com.teach.web.UserController;

@RestController
@RequestMapping("/api/user")
public class UserApi {
	private static final Logger log = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserService userService;
	
	@PostMapping("login")
	public R doLogin(String userName,String userPassword,String code,HttpSession session) {
		try {
			Const.checkKaptcha(session, code);
			LoginUser user = userService.login(userName, userPassword);
			session.setAttribute(Const.SESSION_LOGIN_USER, user);
			return R.ok().setData(user);
		}catch (Exception e) {
			log.debug("登录失败",e);
			return R.error().setMessage(e.getMessage());
		}
	}
	
	@PostMapping("reg")
	public R doReg(UserRegDTO user,String code,HttpSession session) {
		try {
			Const.checkKaptcha(session, code);
			userService.reg(user);
			return R.ok().setData(user); 
		}catch (Exception e) {
			log.debug("注册失败",e);
			return R.error().setMessage(e.getMessage());
		}
	}
	
	@PostMapping("exists")
	public R doExists(String userName) {
		return R.ok().setData(userService.existsUserName(userName));
	}
	
	@GetMapping("page")
	public R doPage(UserSearch search,Page<User> page) {
		return R.ok().setData(userService.page(page, userService.getQueryWrapper(search)));
	}
}
